package top.infopub.mgr.mkt.web;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import top.infopub.dto.mkt.BidDecisionDto;
import top.infopub.enums.mkt.ProProcesssStatusEnum;
import top.infopub.mgr.common.page.ParamPage;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.web.GenericFlowController;
import top.infopub.mgr.mkt.domain.BidCurrencyDomain;
import top.infopub.mgr.mkt.jsonvo.BidDecisionJsonVo;
import top.infopub.mgr.mkt.service.BidDecisionService;
import top.infopub.mgr.mkt.service.BidReviewService;
import top.infopub.mgr.mkt.service.ProProcessManageService;
import top.infopub.mgr.mkt.vo.BidCurrencyVo;
import top.infopub.model.mkt.*;
import top.infopub.security.util.SessionUserUtils;
import top.infopub.security.vo.AuthorizationVO;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 投标决策
 */
@Controller
@RequestMapping("/bidDecision")
public class BidDecisionController extends GenericFlowController {

    @Autowired
    private BidDecisionService bidDecisionService;

    @Autowired
    private ProProcessManageService proProcessManageService;

    @Autowired
    private BidReviewService bidReviewService;


    @RequestMapping("/queryDataByCondition")
    @ResponseBody
    public RspVo<BidCurrencyDomain> queryDataByCondition(BidCurrencyVo bidCurrencyVo,
                                                         ParamPage paramPage) throws ParseException {
        Page<BidCurrencyDomain> page = new Page<BidCurrencyDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        page = bidDecisionService.selectPage(page, bidCurrencyVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    @RequestMapping("/toDealOrDetail")
    public String queryById(HttpServletRequest request, String id, String proCode){
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        request.setAttribute("id", id);
        BidDecision bidDec = bidDecisionService.selectByPrimaryKey(id);
        request.setAttribute("isAuditFlag", "1");
        request.setAttribute("auditTabFlag", "0");
        request.setAttribute("isThoughFlag", "0");
        if (bidDec != null) {
            if (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), bidDec.getProcessStatus())
                    || StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS9.getCode(), bidDec.getProcessStatus())) {
                request.setAttribute("isAuditFlag", "0");
            }
            if (StringUtils.isNotBlank(bidDec.getProcessId()) && bidDec.getProcessId().length() > 10) {
                request.setAttribute("processId", bidDec.getProcessId());
                String auditTabFlag = proProcessManageService.checkShowAuditTab(bidDec.getProcessId(), vo);
                if (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), bidDec.getProcessStatus())
                        && StringUtils.equals("0", auditTabFlag)) {
                    request.setAttribute("isAuditFlag", "0");
                }
                request.setAttribute("auditTabFlag", auditTabFlag);
            }
            //如果审批通过，并且招标文件分析没有数据，开放保存和提交按钮
            if (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS9.getCode(), bidDec.getProcessStatus())) {
                List<BidReview> brList = bidReviewService.queryByProCode(bidDec.getProCode());
                if (brList == null || brList.size() <= 0) {
                    request.setAttribute("isAuditFlag", "1");
                    request.setAttribute("isThoughFlag", "1");
                }
            }
        }
        request.setAttribute("proCode", proCode);
        return "mkt/lay-biddingDecision-detail";
    }

    @RequestMapping("/queryDetailById")
    @ResponseBody
    public RspVo queryDetailById(String id) {
        //投标决策详情信息
        BidDecisionJsonVo bidDecJson = bidDecisionService.queryDetailById(id);
        return RspVo.getSuccessResponse(bidDecJson);
    }

    @RequestMapping("/auditProcess")
    @ResponseBody
    public RspVo auditProcess(String id, String processId, String status, String auditMsg) {
        //投标决策审批
        proProcessManageService.auditProject(id, processId, status, auditMsg, null);
        return RspVo.getSuccessResponse();
    }

    /**
     * 编辑投标决策
     * @param request
     * @return
     */
    @RequestMapping("/edit")
    public @ResponseBody RspVo edit(HttpServletRequest request, String bodyStr, Integer submitType) {
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        String str = StringEscapeUtils.unescapeJava(bodyStr);
        BidDecisionJsonVo bidDecJson = JSON.parseObject(str, BidDecisionJsonVo.class);
        BidDecisionDto bidDecDto = bidDecJson.getInfo();
        //更新项目基础信息表-MKT_PROJECT_INFO
        ProjectInfo proInfo = new ProjectInfo();
        BeanUtils.copyProperties(bidDecDto, proInfo);

        //更新投标决策表-MKT_BID_DECISION
        BidDecision bidDecision = new BidDecision();
        BeanUtils.copyProperties(bidDecDto, bidDecision);

        //更新投标信息表-MKT_BID_INFO
        BidInfo bidInfo = new BidInfo();
        bidInfo.setBondEndDate(bidDecDto.getBondEndDate());
        bidInfo.setBondMoney(bidDecDto.getBondMoney());

        //取出项目风险
        //获取当前阶段
        String node = proProcessManageService.queryProProcessType(bidDecDto.getProCode()).getNode();
        List<ProjectRisk> riskTable = bidDecJson.getRiskTable();
        if (riskTable!=null && riskTable.size()>0)
        {
            for (ProjectRisk risk : riskTable) {
                risk.setRiskStage(node);
                risk.setAddBy(vo.getId());
                risk.setAddTime(new Date());
                risk.setProCode(bidDecDto.getProCode());
            }
            bidDecisionService.insertRiskTable(riskTable);
        }

        //更新附件表-MKT_PROJECT_ATTACHMENT
        List<ProjectAttachment> attachmentList = new ArrayList<>();
        if(bidDecJson.getFileAtt()!=null){
            String[] fileAtt = bidDecJson.getFileAtt();
            for (String file : fileAtt) {
                ProjectAttachment attachment = createProjectFileAtta(vo, bidDecDto.getProCode(), file);
                attachmentList.add(attachment);
            }
        }

        //调用service进行数据库操作
        RspVo rspVo = bidDecisionService.editDetail(proInfo, bidDecision, bidInfo, attachmentList, vo, submitType);
        return rspVo;
    }
}

